package com.mdxl.util;



import org.activiti.engine.impl.persistence.entity.CommentEntity;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chengjian on 2017/4/13.
 */
public class ExportTaskPoi {
   /* public static Boolean exportTaskDetails(TaskInfoDetailsResponse taskInfoDetailsResponse, CategoryModel categoryModel, List<ExternalModel> externalModels, ServletOutputStream out, HttpServletResponse response, HttpServletRequest request) {


        //创建人

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("工单详情列表目录");
        sheet.autoSizeColumn(1);
        sheet.autoSizeColumn(1, true);
       *//* cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        cellStyle.setAlignment(HSSFCellStyle.VERTICAL_CENTER);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);*//*

        // XSSFRow header = sheet.createRow(0);
        // CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 6);
        // sheet.addMergedRegion(cra);
        // for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
        //POI设置列宽度时比较特殊，它的基本单位是1/255个字符大小，
        //因此我们要想让列能够盛的下20个字符的话，就需要用255*20
        //sheet.setColumnWidth(i, 255 * 40);
        // }

        // XSSFRow header = sheet.createRow(0);
        // CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 6);
        // sheet.addMergedRegion(cra);
        // for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
        //POI设置列宽度时比较特殊，它的基本单位是1/255个字符大小，
        //因此我们要想让列能够盛的下20个字符的话，就需要用255*20
        //sheet.setColumnWidth(i, 255 * 40);
        // }

        //header.setHeightInPoints(30);
        //XSSFCell cell0 = header.createCell(0);
        //cell0.setCellValue("工单列表详情");

        //第二行
        XSSFRow Second = sheet.createRow(0);
        CellRangeAddress cra2 = new CellRangeAddress(0, 0, 0, 6);
        sheet.addMergedRegion(cra2);
        Second.setHeightInPoints(20);
        XSSFCell cell1 = Second.createCell(0);
        cell1.setCellValue("工单基本信息");

        //第三行 工单基本信息的详细信息
        XSSFRow Third = sheet.createRow(1);
        Third.createCell(0).setCellValue("工单编号");
        Third.createCell(1).setCellValue("工单类型");
        Third.createCell(2).setCellValue("创建人");
        String candidate = null;
        if (taskInfoDetailsResponse.getCandidateGroupName() == null) {
            Third.createCell(3).setCellValue("经办人");
            candidate = taskInfoDetailsResponse.getCandidateName();
        }
        if (taskInfoDetailsResponse.getCandidateName() == null) {
            Third.createCell(3).setCellValue("经办组");
            candidate = taskInfoDetailsResponse.getCandidateGroupName();
        }
        Third.createCell(4).setCellValue("优先级");
        Third.createCell(5).setCellValue("状态");
        Third.createCell(6).setCellValue("创建时间");
        sheet.setColumnWidth((short) 0, (short) 7000);
        sheet.setColumnWidth((short) 1, (short) 10000);
        sheet.setColumnWidth((short) 2, (short) 4000);
        sheet.setColumnWidth((short) 3, (short) 4000);
        sheet.setColumnWidth((short) 4, (short) 4000);
        sheet.setColumnWidth((short) 5, (short) 4000);
        sheet.setColumnWidth((short) 6, (short) 7000);
        //接下来，在第四行放入 字段数据
        XSSFRow Four = sheet.createRow(2);
        //创建工单状态集合map，并根据key取出相应的value
        Map<String, String> statusMap = new HashMap<>();
        statusMap.put("Created", "创建");
        statusMap.put("Waiting", "待处理");
        statusMap.put("Handling", "处理中");
        statusMap.put("Finished", "已关闭");
        //优先级
        Map<Integer, String> priorityMap = new HashMap<>();
        priorityMap.put(1, "普通");
        priorityMap.put(2, "重要");
        priorityMap.put(3, "紧急");
        //创建时间的转换
        String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(taskInfoDetailsResponse.getCreateTime());
        Four.createCell(0).setCellValue(taskInfoDetailsResponse.getNumber());
        Four.createCell(1).setCellValue(taskInfoDetailsResponse.getCategoryName());
        Four.createCell(2).setCellValue(taskInfoDetailsResponse.getCreatorName());
        Four.createCell(3).setCellValue(candidate);
        Four.createCell(4).setCellValue(priorityMap.get(taskInfoDetailsResponse.getPriority()));
        Four.createCell(5).setCellValue(statusMap.get(taskInfoDetailsResponse.getStatus()));
        Four.createCell(6).setCellValue(createTime);

     *//*   //创建第五行 用户信息
        XSSFRow Five = sheet.createRow(4);
        XSSFCell cell2 = Five.createCell(0);
        cell2.setCellValue("用户信息");
        CellRangeAddress cra3 = new CellRangeAddress(4, 4, 0, 6);
        sheet.addMergedRegion(cra3);
        //创建第六行，用户信息的具体信息目录标题
        XSSFRow Six = sheet.createRow(5);
        Six.createCell(0).setCellValue("用户名");
        Six.createCell(1).setCellValue("姓名");
        Six.createCell(2).setCellValue("手机");
        Six.createCell(3).setCellValue("英文名");
        Six.createCell(4).setCellValue("出生日期");
        Six.createCell(5).setCellValue("座机");
        XSSFRow Seven = sheet.createRow(6);
        if(user != null) {
            String u_name = user.get("u_name").toString();
            String u_birthday = user.get("u_birthday").toString();
            String u_registername = user.get("u_registername").toString();
            String u_englishname = user.get("u_englishname").toString();
            String u_mobilephone = user.get("u_mobilephone").toString();
            String u_telephone = user.get("u_telephone").toString();
            Seven.createCell(0).setCellValue(u_name);
            Seven.createCell(1).setCellValue(u_registername);
            Seven.createCell(2).setCellValue(u_mobilephone);
            Seven.createCell(3).setCellValue(u_englishname);
            Seven.createCell(4).setCellValue(u_birthday);
            Seven.createCell(5).setCellValue(u_telephone);
        }

*//*
        //创建第八行
        XSSFRow Eight = sheet.createRow(4);
        XSSFCell cell3 = Eight.createCell(0);
        cell3.setCellValue("工单记录");
        CellRangeAddress cra4 = new CellRangeAddress(4, 4, 0, 1);
        sheet.addMergedRegion(cra4);
        int taskRecordNumber;
        int qq = 0;
        for (taskRecordNumber = 0; taskRecordNumber < taskInfoDetailsResponse.getHistories().size(); taskRecordNumber++) {
            List<CommentEntity> comments = taskInfoDetailsResponse.getHistories().get(taskRecordNumber).getComments();
            //从第九行开始创建

            String taskRecoreTime = null;
            String message2 = null;
            for (int j = 0; j < comments.size(); j++) {
                //工单记录的进展,不过此时的字符串需要切割成理想状态
                int total = taskInfoDetailsResponse.getHistories().size() + comments.size() - 1;
                qq = total;

                XSSFRow NineAdd = sheet.createRow(5 + taskRecordNumber + j);
                String message = comments.get(j).getMessage();
                String[] message1 = message.split("\\|");
                int a = message1.length;
                message2 = message1[a - 2] + " " + message1[a - 1];
                //工单记录的时间显示
                taskRecoreTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(comments.get(j).getTime());
                //如果有数据的话，那么在此行显示
                NineAdd.createCell(0).setCellValue(taskRecoreTime);
                NineAdd.createCell(1).setCellValue(message2);

            }
        }

        //工单信息，从n行开始创建
        XSSFRow nRow = sheet.createRow(6 + qq);
        XSSFCell cellDe = nRow.createCell(0);
        cellDe.setCellValue("工单信息");
        CellRangeAddress cra5 = new CellRangeAddress(6 + qq, 6 + qq, 0, 1);
        sheet.addMergedRegion(cra5);
        int ii = 0;
        List<FieldModel> fields = categoryModel.getFields();
        for (int cc = 0; cc < fields.size(); cc++) {
            XSSFRow nRow1 = sheet.createRow(7 + qq + cc);
            ii = 11 + qq + cc;
            FieldModel fieldModel = fields.get(cc);
            String title = fieldModel.getTitle();
            nRow1.createCell(0).setCellValue(title);

            String valueInfo = "c_" + fieldModel.getCode();
            List<Map<String, Object>> variables = taskInfoDetailsResponse.getVariables();
            for (int dd = 0; dd < variables.size(); dd++) {
                Map<String, Object> variableMap = variables.get(dd);
                String value = variableMap.get("name").toString();
                if (value.equals(valueInfo)) {

                    if (fieldModel.getValueType().equals("options")) {


                        String value1 = variableMap.get("value").toString();

                        String json = fieldModel.getOptionJson();


                        JSONArray jsonArray = JSONArray.fromObject(json);
                        List<Map<String, Object>> mapListJson = (List) jsonArray;


                        for (int i = 0; i < mapListJson.size(); i++) {
                            Map<String, Object> obj = mapListJson.get(i);
                            String titleww = obj.get("value").toString();
                            if (obj != null && titleww.equals(value1)) {
                                nRow1.createCell(1).setCellValue(obj.get("title").toString());
                            }
                        }
                    } else {
                        nRow1.createCell(1).setCellValue(variableMap.get("value").toString());
                    }

                        *//*else {
                            String value1=variableMap.get("value").toString();
                            //放入json数据选title
                            String json =fieldModel.getOptionJson();
                            JSONArray jsonArray = JSONArray.fromObject(json);
                            List<Map<String,Object>> mapListJson = (List)jsonArray;
                            for (int i = 0; i < mapListJson.size(); i++) {
                                Map<String, Object> obj = mapListJson.get(i);
                                String titleww = obj.get("title").toString();
                                if (obj !=null && obj.get("value").equals(value1)){
                                    nRow1.createCell(1).setCellValue(titleww);
                                }
                            }
                        }*//*
                }
            }
        }

        //外部信息的显示
        XSSFRow nRowIi = sheet.createRow(ii + 1);
        XSSFCell cellDe1 = nRowIi.createCell(0);
        cellDe1.setCellValue("外部信息");
        CellRangeAddress cra6 = new CellRangeAddress(ii, ii, 0, 1);
        sheet.addMergedRegion(cra6);
        int aa = ii + 2;
        for (int i = 0; i < externalModels.size(); i++) {
            ExternalModel externalModel = externalModels.get(i);

            XSSFRow nRowIi1 = sheet.createRow(aa + i);
            nRowIi1.createCell(0).setCellValue(externalModel.getTitleName());
            if (externalModel.getParamModelList() != null) {
                nRowIi1.createCell(1).setCellValue(externalModel.getParamModelList().get(0).getTitle());
                for (int j = 1; j < externalModel.getParamModelList().size(); j++) {
                    XSSFRow nRowIi2 = sheet.createRow(aa + i + j);
                    nRowIi2.createCell(1).setCellValue(externalModel.getParamModelList().get(j).getTitle());
                }
                aa += externalModel.getParamModelList().size() - 1;
            }
        }

        //此时此刻时间
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        Random random = new Random();


        //下面是新加客户端代码

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        String fileName = dateString + random.nextInt() + ".xlsx";
        String agent = request.getHeader("USER-AGENT");
        if (null != agent && -1 != agent.indexOf("MSIE") || null != agent
                && -1 != agent.indexOf("Trident")) {// ie
            String name = null;
            try {
                name = java.net.URLEncoder.encode(fileName, "UTF8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            fileName = name;
        } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
            try {
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//new String((fileName + ".xls").getBytes(), "iso-8859-1")
        //ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            try {
                throw e;
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return true;

        //上面设置好了内容，我们当然是要输出到某个文件的，输出就需要有输出流

        //这是添加到服务器端代码
           *//* try {
                FileOutputStream fos = new FileOutputStream("d:/" + dateString + random.nextInt() + ".xlsx");
                wb.write(fos);
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
*//*
    }
*/

}
